package com.century.sjt.EMChat.fragment;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.century.sjt.SjtHelper;
import com.century.sjt.activity.AddressAddActivity;
import com.century.sjt.EMChat.activity.ChatRoomDetailsActivity;
import com.century.sjt.EMChat.activity.ContextMenuActivity;
import com.century.sjt.EMChat.activity.ForwardMessageActivity;
import com.century.sjt.EMChat.activity.GroupDetailsActivity;
import com.century.sjt.EMChat.activity.ImageGridActivity;
import com.century.sjt.EMChat.activity.VideoCallActivity;
import com.century.sjt.EMChat.activity.VoiceCallActivity;
import com.century.sjt.activity.Pay.CommodityActivity;
import com.century.sjt.activity.Pay.CommodityListActivity;
import com.century.sjt.activity.Pay.TransactionDataActivity;
import com.century.sjt.activity.Topic.MyTopActivity;
import com.century.sjt.activity.QRRecordCodeScanActivity;
//import com.century.sjt.activity.RemitMoneyActivity;
//import com.century.sjt.activity.TransactionDataActivity;
import com.century.sjt.adapter.AddressAdapter;
import com.century.sjt.EMChat.db.DraftDao;
import com.century.sjt.entity.Address;
import com.century.sjt.entity.MyDraft;
import com.century.sjt.util.Check;
import com.century.sjt.util.TipUtil;
import com.century.sjt.window.AddressWindow;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMGroup;
import com.easemob.chat.EMGroupManager;
import com.easemob.chat.EMMessage;
import com.easemob.chat.TextMessageBody;
import com.century.sjt.EMChat.utils.EaseConstant;
import com.century.sjt.EMChat.domain.EaseUser;
//import com.century.sjt.EMChat.ui.EaseChatFragment;
//import com.century.sjt.EMChat.ui.EaseChatFragment.EaseChatFragmentListener;
import com.century.sjt.EMChat.utils.EaseUserUtils;
import com.century.sjt.EMChat.widget.chatrow.EaseChatRow;
import com.century.sjt.EMChat.widget.chatrow.EaseCustomChatRowProvider;
import com.century.sjt.EMChat.widget.emojicon.EaseEmojiconMenu;
import com.easemob.util.PathUtil;
import com.century.sjt.Constant;
import com.century.sjt.R;
import com.century.sjt.domain.EmojiconExampleGroupData;
import com.century.sjt.domain.RobotUser;
import com.century.sjt.widget.ChatRowVoiceCall;
import com.century.sjt.EMChat.fragment.EaseChatFragment.EaseChatFragmentListener;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ChatFragment extends EaseChatFragment implements EaseChatFragmentListener {

    //避免和基类定义的常量可能发生的冲突，常量从11开始定义
    private static final int ITEM_VIDEO = 11;
    private static final int ITEM_FILE = 12;
    private static final int ITEM_VOICE_CALL = 13;
    private static final int ITEM_VIDEO_CALL = 14;
    private static final int ITEM_REMIT_MONEY = 81;
    private static final int ITEM_REMIT_ADDRESS = 99;
    private static final int ITEM_INPUT_ORDER = 98;
    private static final int ITEM_REMIT_PAY=100;



    private static final int REQUEST_CODE_SELECT_VIDEO = 11;
    private static final int REQUEST_CODE_SELECT_FILE = 12;
    private static final int REQUEST_CODE_GROUP_DETAIL = 13;
    private static final int REQUEST_CODE_CONTEXT_MENU = 14;

    private static final int MESSAGE_TYPE_SENT_VOICE_CALL = 1;
    private static final int MESSAGE_TYPE_RECV_VOICE_CALL = 2;
    private static final int MESSAGE_TYPE_SENT_VIDEO_CALL = 3;
    private static final int MESSAGE_TYPE_RECV_VIDEO_CALL = 4;


    /**
     * 是否为环信小助手
     */
    private boolean isRobot;



    private List<Address> mDatalist = new ArrayList<>();
    private ListView listAddress;
    private AddressAdapter madapter;
    private Handler mHandler;
    private Dialog mProgressDialog;
    private Dialog mDialog;
    private LinearLayout llCancel;

    private List<String> list = new ArrayList<String>();

    private EditText etGoodName;
    private EditText etGoodType;
    private EditText etCount;
    private EditText etSpecification;
    private EaseUser toChatUser = null;

    private MyDraft myDraft;
    private String textDrraft = "";


    private boolean isMsgSpeaker=true;
    private boolean isOpenBaiduTranslate = false;
    private String isShop,isMerchant;

    private AddressWindow addressWindow;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    protected void setUpView() {

        SharedPreferences mainSharedPreferences = getActivity().getSharedPreferences(com.century.sjt.util.Constant.TAG, Activity.MODE_PRIVATE);
        isShop = mainSharedPreferences.getString("isShop", "");
        isMerchant = mainSharedPreferences.getString("isMerchant","");
        if (chatType == EaseConstant.CHATTYPE_SINGLE) { // 单聊
            // 设置标题
            if(EaseUserUtils.getUserInfo(toChatUsername) != null){
//                titleBar.setTitle(EaseUserUtils.getUserInfo(toChatUsername).getNick());
            }

        } else {
            if (chatType == EaseConstant.CHATTYPE_GROUP) {
                // 群聊
                EMGroup group = EMGroupManager.getInstance().getGroup(toChatUsername);
                if (group != null)
//                    titleBar.setTitle(group.getGroupName());
                // 监听当前会话的群聊解散被T事件
                groupListener = new GroupListener();
                EMGroupManager.getInstance().addGroupChangeListener(groupListener);
            } else {
                onChatRoomViewCreation();
            }

        }
        if (chatType != EaseConstant.CHATTYPE_CHATROOM) {
            onConversationInit();
            onMessageListInit();
        }



        setChatFragmentListener(this);
        if (chatType == Constant.CHATTYPE_SINGLE) {
            Map<String, RobotUser> robotMap = SjtHelper.getInstance().getRobotList();
            if (robotMap != null && robotMap.containsKey(toChatUsername)) {
                isRobot = true;
            }
        }
        super.setUpView();
        ((EaseEmojiconMenu) inputMenu.getEmojiconMenu()).addEmojiconGroup(EmojiconExampleGroupData.getData());
    }

    @Override
    protected void registerExtendMenuItem() {
        //demo这里不覆盖基类已经注册的item,item点击listener沿用基类的
        super.registerExtendMenuItem();

        //增加扩展item
//        inputMenu.registerExtendMenuItem(R.string.attach_video, R.drawable.em_chat_video_selector, ITEM_VIDEO, extendMenuItemClickListener);
//        inputMenu.registerExtendMenuItem(R.string.attach_file, R.drawable.em_chat_file_selector, ITEM_FILE, extendMenuItemClickListener);
        if (chatType == Constant.CHATTYPE_SINGLE) {
//            inputMenu.registerExtendMenuItem(R.string.attach_voice_call, R.drawable.em_chat_voice_call_selector, ITEM_VOICE_CALL, extendMenuItemClickListener);
//            inputMenu.registerExtendMenuItem(R.string.attach_video_call, R.drawable.em_chat_video_call_selector, ITEM_VIDEO_CALL, extendMenuItemClickListener);
//            inputMenu.registerExtendMenuItem("转账", R.mipmap.char_zz, ITEM_REMIT_MONEY, extendMenuItemClickListener);
            inputMenu.registerExtendMenuItem(getResources().getString(R.string.text_address_recipient), getResources().getString(R.string.icon_shortcut), ITEM_REMIT_ADDRESS, extendMenuItemClickListener);
            SharedPreferences mainSharedPreferences = getActivity().getSharedPreferences(com.century.sjt.util.Constant.TAG, Activity.MODE_PRIVATE);
            String isShop = mainSharedPreferences.getString("isShop", "");
            toChatUser = SjtHelper.getInstance().getUser(toChatUsername);
//            if (isShop.equals("1")) {
//                inputMenu.registerExtendMenuItem(getResources().getString(R.string.text_logistic_information),getResources().getString(R.string.icon_store) , ITEM_INPUT_ORDER, extendMenuItemClickListener);
//            }else {
//
//                if (toChatUser.getShopId()==null||"".equals(toChatUser.getShopId())){
//                }else {
//
//                    inputMenu.registerExtendMenuItem(getResources().getString(R.string.text_pay), R.mipmap.payx, ITEM_REMIT_PAY, extendMenuItemClickListener);
//                }
//            }

        }


    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CONTEXT_MENU) {
            switch (resultCode) {
                case ContextMenuActivity.RESULT_CODE_COPY: // 复制消息
                    clipboard.setText(((TextMessageBody) contextMenuMessage.getBody()).getMessage());
                    break;
                case ContextMenuActivity.RESULT_CODE_DELETE: // 删除消息
                    conversation.removeMessage(contextMenuMessage.getMsgId());
                    messageList.refresh();
                    break;

                case ContextMenuActivity.RESULT_CODE_FORWARD: // 转发消息
                    Intent intent = new Intent(getActivity(), ForwardMessageActivity.class);
                    intent.putExtra("forward_msg_id", contextMenuMessage.getMsgId());
                    startActivity(intent);
                    break;
                case ContextMenuActivity.RESULT_CODE_TRANSLATE: // 翻译
                    baiduTranslate.translate(getActivity(),mQueue,contextMenuMessage, "zh", "en");
                    break;
                default:
                    break;
            }
        }
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_SELECT_VIDEO: //发送选中的视频
                    if (data != null) {
                        int duration = data.getIntExtra("dur", 0);
                        String videoPath = data.getStringExtra("path");
                        File file = new File(PathUtil.getInstance().getImagePath(), "thvideo" + System.currentTimeMillis());
                        try {
                            FileOutputStream fos = new FileOutputStream(file);
                            Bitmap ThumbBitmap = ThumbnailUtils.createVideoThumbnail(videoPath, 3);
                            ThumbBitmap.compress(CompressFormat.JPEG, 100, fos);
                            fos.close();
                            sendVideoMessage(videoPath, file.getAbsolutePath(), duration);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    break;
                case REQUEST_CODE_SELECT_FILE: //发送选中的文件
                    if (data != null) {
                        Uri uri = data.getData();
                        if (uri != null) {
                            sendFileByUri(uri);
                        }
                    }
                    break;

                default:
                    break;
            }
        }
        //扫描二维码返回的信息(录入订单)
//        qrRecordCodeResult(requestCode, resultCode, data);

    }

    @Override
    public void onSetMessageAttributes(EMMessage message) {
        if (isRobot) {
            //设置消息扩展属性
            message.setAttribute("em_robot_message", isRobot);
        }
    }
    @Override
    public void onSetTextChanged(String content) {

        if ("".equals(content)||null==content){
//            Log.e("text","11");
        }else {
            textDrraft=content;
        }
    }

    @Override
    public EaseCustomChatRowProvider onSetCustomChatRowProvider() {
        //设置自定义listview item提供者
        return new CustomChatRowProvider();
    }


    @Override
    public void onEnterToChatDetails() {
        if (chatType == Constant.CHATTYPE_GROUP) {
            EMGroup group = EMGroupManager.getInstance().getGroup(toChatUsername);
            if (group == null) {
                Toast.makeText(getActivity(), R.string.gorup_not_found,
                        0).show();
                return;
            }

            startActivityForResult(
                    (new Intent(getActivity(), GroupDetailsActivity.class).putExtra("groupId", toChatUsername)),
                    REQUEST_CODE_GROUP_DETAIL);
        } else if (chatType == Constant.CHATTYPE_CHATROOM) {
            startActivityForResult(new Intent(getActivity(), ChatRoomDetailsActivity.class).putExtra("roomId", toChatUsername), REQUEST_CODE_GROUP_DETAIL);
        }
    }

    @Override
    public void onAvatarClick(String username) {
        SharedPreferences mainSharedPreferences = getActivity().getSharedPreferences(com.century.sjt.util.Constant.TAG, Activity.MODE_PRIVATE);
        String userId = mainSharedPreferences.getString("userId", "");
        //头像点击事件
        if (username.equals("00000000")) {

        }else if(username.equals(userId)){//如果点击的是自己的头像不处理

        }else {
            Intent intent = new Intent(getActivity(), MyTopActivity.class);
            intent.putExtra("username", username);
            startActivity(intent);
        }

    }

    @Override
    public boolean onMessageBubbleClick(EMMessage message) {
        //消息框点击事件，demo这里不做覆盖，如需覆盖，return true
        //TODO 消息框点击事件
        int type = message.getType().ordinal();
        EMMessage message1 = message;
        if (type == EMMessage.Type.TXT.ordinal()) {
            String ext_type = message.getStringAttribute("ext_type",null);
            switch (ext_type){
                case "1":
                    String ext_orderId = message.getStringAttribute("ext_orderId",null);
                    if (null!=ext_orderId||"".equals(ext_orderId)){
                        Intent intent = new Intent(getActivity(), TransactionDataActivity.class);
                        intent.putExtra("payType", "5");
                        intent.putExtra("txNo", ext_orderId);
                        intent.putExtra("Type",ext_type);
                        intent.putExtra("orderId", ext_orderId);
                        intent.putExtra("title", getResources().getString(R.string.tab_pay_picture));
                        startActivity(intent);
                    }

                    break;
                case "2":
                    Intent intent = new Intent(getActivity(), CommodityActivity.class);
                    intent.putExtra("url", message.getStringAttribute("detailsUrl",null));
                    intent.putExtra("shopId",message.getStringAttribute("shopId",null));
                    intent.putExtra("goodId",message.getStringAttribute("goodId",null));
                    intent.putExtra("shareUrl",message.getStringAttribute("shareUrl",null));
                    intent.putExtra("goodName",message.getStringAttribute("goodName",null));
                    intent.putExtra("mainImageUrl",message.getStringAttribute("mainImageUrl",null));
                    intent.putExtra("shopUserId",message.getStringAttribute("shopUserId",null));
                    intent.putExtra("price",message.getStringAttribute("price",null));
                    startActivity(intent);
                    break;
            }


        }
        return false;
    }

    @Override
    public void onMessageBubbleLongClick(EMMessage message) {
        //消息框长按
        startActivityForResult((new Intent(getActivity(), ContextMenuActivity.class)).putExtra("message", message),
                REQUEST_CODE_CONTEXT_MENU);
    }

    @Override
    public boolean onExtendMenuItemClick(int itemId, View view) {
        switch (itemId) {
            case ITEM_VIDEO: //视频
                Intent intent = new Intent(getActivity(), ImageGridActivity.class);
                startActivityForResult(intent, REQUEST_CODE_SELECT_VIDEO);
                break;
            case ITEM_FILE: //一般文件
                //demo这里是通过系统api选择文件，实际app中最好是做成qq那种选择发送文件
                selectFileFromLocal();
                break;
//            case ITEM_VOICE_CALL: //音频通话
//                startVoiceCall();
//                break;
//            case ITEM_VIDEO_CALL: //视频通话
//                startVideoCall();
//                break;
//            case ITEM_REMIT_MONEY: //转账
//                startRemitMoney();
//                break;
            case ITEM_REMIT_ADDRESS: //收货地址
                initData();
                break;
            case ITEM_REMIT_PAY: //支付
//                shopDetail(toChatUser.getShopId());
                break;
            case ITEM_INPUT_ORDER: //录入订单
                inputOrder();
                break;
            default:
                break;
        }
        //不覆盖已有的点击事件
        return false;
    }


    /**
     * 选择文件
     */
    protected void selectFileFromLocal() {
        Intent intent = null;
        if (Build.VERSION.SDK_INT < 19) { //19以后这个api不可用，demo这里简单处理成图库选择图片
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("*/*");
            intent.addCategory(Intent.CATEGORY_OPENABLE);

        } else {
            intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        }
        startActivityForResult(intent, REQUEST_CODE_SELECT_FILE);
    }

    /**
     * 拨打语音电话
     */
    protected void startVoiceCall() {
        if (!EMChatManager.getInstance().isConnected()) {
            Toast.makeText(getActivity(), R.string.not_connect_to_server, 0).show();
        } else {
            startActivity(new Intent(getActivity(), VoiceCallActivity.class).putExtra("username", toChatUsername)
                    .putExtra("isComingCall", false));
            // voiceCallBtn.setEnabled(false);
            inputMenu.hideExtendMenuContainer();
        }
    }

    //获取地址接口
    private void getAddress() {
//        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.please_waitting), AddressManageActivity.this);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, com.century.sjt.util.Constant.queryReceiver, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
//                    TipUtil.closeProgressDialog();
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    TipUtil.log("获取地址", res.toString(), 1);
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {//成功
                        if (res.getJSONArray("data").length() == 0) {
//                            TipUtil.showToast("", AddressManageActivity.this);
                            showAppayRes();
                        } else {
                            mDatalist.clear();
                            JSONArray data = res.getJSONArray("data");
                            for (int i = 0; i < data.length(); i++) {

                                JSONObject aData = (JSONObject) data.get(i);
                                Address address = new Address();
                                address.setSysId(aData.getString("sysId"));
                                address.setAddress(aData.getString("address"));
                                address.setAreaName(aData.getString("areaName"));
                                address.setConsignee(aData.getString("consignee"));
                                address.setIsDefault(aData.getString("isDefault"));
                                address.setPhone(aData.getString("phone"));
                                address.setIpCode(aData.getString("zipCode"));
                                address.setArexz(aData.getString("areaName"));
                                address.setUserId(aData.getString("userId"));
                                mDatalist.add(address);
                            }
                            addressWindow.setDataList(mDatalist);
                            addressWindow.showAtLocation(getActivity().findViewById(R.id.chatview), Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
//                            Message msg = new Message();
//                            msg.what = 1;
//                            mHandler.sendMessage(msg);
                        }
                    } else {//失败
                        TipUtil.showToast(message, getActivity(), 1);
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getResources().getString(R.string.error_service), getActivity(), 1);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getResources().getString(R.string.error_network), getActivity(), 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences = getActivity().getSharedPreferences(com.century.sjt.util.Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
                map.put("loginId", userId);
//                map.put("paging.currentPage",String.valueOf(iCurrPage));//当前页码
//                map.put("paging.pageSize",Constant.PAGESIZE+" ");//查询条数

                return map;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = getActivity().getSharedPreferences(com.century.sjt.util.Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);

    }


    /**
     * 拨打视频电话
     */
    protected void startVideoCall() {
        SharedPreferences mainSharedPreferences = getActivity().getSharedPreferences(com.century.sjt.util.Constant.TAG, Activity.MODE_PRIVATE);
        String userId = mainSharedPreferences.getString("userId", "");
        String image = mainSharedPreferences.getString("image", "");
        String nickName = mainSharedPreferences.getString("nickName", "");
        String mobile = mainSharedPreferences.getString("mobile", "");
        ChatToMesage(nickName, toChatUsername);
        if (!EMChatManager.getInstance().isConnected())
            Toast.makeText(getActivity(), R.string.not_connect_to_server, 0).show();
        else {
            startActivity(new Intent(getActivity(), VideoCallActivity.class).putExtra("username", toChatUsername)
                    .putExtra("isComingCall", false));
            // videoCallBtn.setEnabled(false);
            inputMenu.hideExtendMenuContainer();
        }
    }

    /**
     * chat row provider
     */
    private final class CustomChatRowProvider implements EaseCustomChatRowProvider {
        @Override
        public int getCustomChatRowTypeCount() {
            //音、视频通话发送、接收共4种
            return 4;
        }

        @Override
        public int getCustomChatRowType(EMMessage message) {
            if (message.getType() == EMMessage.Type.TXT) {
                //语音通话类型
                if (message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_VOICE_CALL, false)) {
                    return message.direct == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_VOICE_CALL : MESSAGE_TYPE_SENT_VOICE_CALL;
                } else if (message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_VIDEO_CALL, false)) {
                    //视频通话
                    return message.direct == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_VIDEO_CALL : MESSAGE_TYPE_SENT_VIDEO_CALL;
                }
            }
            return 0;
        }

        @Override
        public EaseChatRow getCustomChatRow(EMMessage message, int position, BaseAdapter adapter) {
            if (message.getType() == EMMessage.Type.TXT) {
                // 语音通话,  视频通话
                if (message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_VOICE_CALL, false) ||
                        message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_VIDEO_CALL, false)) {
                    return new ChatRowVoiceCall(getActivity(), message, position, adapter);
                }
            }
            return null;
        }
    }


    public void ChatToMesage(String userName, String toChatUsername) {
        sendTextMessage(getResources().getString(R.string.text_you_friend) + userName + " "+getResources().getString(R.string.text_request_call));
//        EMMessage message = EMMessage.createTxtSendMessage("您的好友:"+userName+" 请求通话", toChatUsername);
//        //发送消息
//        EMChatManager.getInstance().sendMessage(message, null);
    }

    public void getAddressToMessage(String address, String toChatUsername) {
        sendAddressMessage(address);
//        EMMessage message = EMMessage.createTxtSendMessage(address, toChatUsername);
//        //发送消息
//        EMChatManager.getInstance().sendMessage(message, null);

    }

    private void initData() {
        addressWindow = new AddressWindow(getActivity(),mDatalist,mQueue);
        addressWindow.setAddressWindowListItemClickListener(new AddressWindow.AddressWindowListItemClickListener() {
            @Override
            public void onItemClick(Address message) {
                String aname = message.getConsignee();
                String address = message.getAddress();
                String phome = message.getPhone();
                String toAddress = aname + "\n" + phome + "\n" + address;

                getAddressToMessage(toAddress, toChatUsername);
            }

            @Override
            public void onDismissClick() {

            }
        });
        getAddress();


    }

    public void showAppayRes() {
        //询问是否取消
        mProgressDialog.dismiss();
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle(getResources().getString(R.string.text_prompt));
        builder.setMessage(getResources().getString(R.string.error_no_one_address));
        builder.setPositiveButton(getResources().getString(R.string.btn_yes), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                Intent intent = new Intent();
                intent.putExtra("Type", "4");
                intent.setClass(getActivity(), AddressAddActivity.class);
                startActivity(intent);
            }
        });
        builder.setNegativeButton(getResources().getString(R.string.btn_no), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.setCancelable(false);
        builder.create().show();
    }

    /**
     * 录入订单 跳转扫描条形码
     */
    private void inputOrder() {
        //跳转到扫描二维码
        Intent intent = new Intent();
        intent.setClass(getActivity(), QRRecordCodeScanActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivityForResult(intent, com.century.sjt.util.Constant.SCANNIN_GREQUEST_CODE);
    }



    @Override
    public void onPause() {
        DraftDao draftDao = new DraftDao(getActivity());
        textDrraft = inputMenu.onGetEditTextEvent();
        SharedPreferences mainSharedPreferences =getActivity().getSharedPreferences(com.century.sjt.util.Constant.TAG, Activity.MODE_PRIVATE);
        String userId = mainSharedPreferences.getString("userId", "");
        if ("".equals(textDrraft.trim())||null==textDrraft){
            //获取草稿
            myDraft = draftDao.getDraftDao(userId,toChatUsername);
            if (myDraft!=null)
                draftDao.deleteDraftDao(toChatUsername);
        }else {

            MyDraft myDraft = new MyDraft();
            myDraft.setMtext(textDrraft);
            myDraft.setUserId(userId);
            myDraft.setFrom(toChatUsername);
            draftDao.saveDraftDao(myDraft);
            EMChatManager.getInstance().saveMessage(SentTextMsg(toChatUsername,userId,textDrraft));
        }

        super.onPause();
    }

    //创建一条发送TextMsg
    private EMMessage SentTextMsg(String toUserId,String userId,String txt) {
        EMMessage msg = EMMessage.createSendMessage(EMMessage.Type.TXT);
        msg.setAttribute("Draft","myDraft");
        TextMessageBody body = new TextMessageBody("[草稿] " + txt);
        msg.addBody(body);
        msg.setTo(toUserId);
        msg.setFrom(userId);
        msg.setMsgTime(System.currentTimeMillis());
        return msg;
    }


}
